<?php

App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');



class UsersController extends AppController {

	public $components = array('Paginator', 'Session');

	public function beforeFilter(){
		$this->Auth->userScope = array('User.active' => 1);
		$this->Auth->allow('index','register','agent_detail','forgot_password','reset_password');
		parent::beforeFilter();
	}


	public function login() {
		$this->set('title_for_layout', 'Login');
		if($this->Auth->user('id'))
				return $this->redirect(array('action' => 'index'));
		if ($this->request->is('post')) {
				if ($this->Auth->login()) {

					if($this->Auth->user('active')!=1){
					$this->Session->setFlash(__('Your account has been suspended.'),'error');
					return $this->redirect(array('action'=>'logout'));
					}
					if($this->Auth->user('approved')!=1){
					$this->Session->setFlash(__('Your account has been Not approved. Please provide required documents.'),'error');
					return $this->redirect(array('action'=>'edit_agent_profile'));
					}
					
					$broker_id	=	$this->Auth->user('broker_id');
					$this->broker($broker_id);

					if($this->Auth->user('user_role')=='admin')
					return $this->redirect(array('action'=>'index','admin'=>true));
					
					return $this->redirect(array('action'=>'edit_agent_profile'));
					return $this->redirect($this->Auth->redirectUrl());
				}
				$this->Session->setFlash(__('Invalid Email or password, try again'),'error');
			}
		}

	private function broker($user_id=null) {

		if(isset($user_id) and !empty($user_id)){
			$User	=	$this->User->findByIdAndActive($user_id,1);
			if(empty($User))
			{
				$this->Session->setFlash(__('Your Broker account has been suspended.'),'error');
				return $this->redirect(array('action'=>'logout'));
			}
		}
		return true;

	}

	public function register() {exit;
		$this->set('title_for_layout', 'Get Register');
		if($this->Auth->user('id'))
				return $this->redirect(array('action' => 'index'));

		if ($this->request->is('post')) {
			$this->User->create();
			$this->request->data['User']['approved']	=	0;
			//$this->request->data['User']['active']	=	0;
			//$this->request->data['User']['email_verified']	=	0;
			//$this->request->data['User']['tokken']	=	 Security::generateAuthKey().''.Security::generateAuthKey();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('You have registered successfully. Please check your email. and follow instructions to activate you account.'), 'default', array('class' => 'alert alert-success'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error');
			}
		}
	}
	public function new_agent() {
		$this->set('title_for_layout', 'Add New Agent');
 		$user_id	=	$this->Auth->user('id');

 		$user_role	=	$this->Auth->user('user_role');
		if(($user_role!='broker_admin'))
				return $this->redirect(array('controller' => 'Pages','action' => 'index'));


		if ($this->request->is('post')) {
			$this->User->create();

			$this->request->data['User']['broker_id']	=	$user_id;
			$this->request->data['User']['user_role']	=	'broker_agent';

			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The agent has been saved.'), 'default', array('class' => 'alert alert-success'));
				return $this->redirect(array('action' => 'my_agents'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error');
			}
		}
	}

	public function my_agents() {
		 $this->set('title_for_layout', 'My Agents');
 		$user_id	=	$this->Auth->user('id');
 		$user_role	=	$this->Auth->user('user_role');
		if(($user_role!='broker_admin'))
				return $this->redirect(array('controller' => 'Pages','action' => 'index'));

		$this->User->recursive = 0;
		$this->set('my_agents', $this->Paginator->paginate(array('User.broker_id'=>$user_id)));
		}

 	public function edit_agent($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		 $this->set('title_for_layout', 'Edit My Agent');
		$broker_id	=	$this->Auth->user('id');

 		$user_role	=	$this->Auth->user('user_role');
		if(($user_role!='broker_admin'))
				return $this->redirect(array('controller' => 'Pages','action' => 'index'));


		if ($this->request->is(array('post', 'put'))) {
			$this->request->data['User']['id']	=	$id;
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'), 'default', array('class' => 'alert alert-success'));
				return $this->redirect(array('action' => 'my_agents'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error', array('class' => 'alert alert-danger'));
			}
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id,'User.broker_id' => $broker_id));
			$user	=	 $this->User->find('first', $options);
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id,'User.broker_id' => $broker_id));
			$this->request->data = $user	=	 $this->User->find('first', $options);
		}
		if(empty($user))
				return $this->redirect(array('controller' => 'Pages','action' => 'index'));

		$this->set('user',$user);
	}


	public function index($user_role	=	'broker_admin') {
		if($user_role=='broker_admin')
			$user_role	=	'broker_admin';
			else
			$user_role	=	'agent';
			

		
		 $this->set('title_for_layout', 'Agents');
		$this->User->recursive = 0;
		$this->set('users', $this->Paginator->paginate(array('User.expiry_date >= ' => date('Y-m-d H:i'),'User.broker_id'=>0,'User.active'=>1, 'User.approved'=>1,'User.user_role'=>array($user_role))));


		$this->set('user_role', $user_role);
	}

	public function agent_detail($id = null) {
		 $this->set('title_for_layout', 'Agent Detail');
		$this->loadModel('Property');
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		
		$options = array('conditions' => array('User.expiry_date >= ' => date('Y-m-d H:i'),'User.active' =>1,'User.approved'=>1,'User.' . $this->User->primaryKey => $id));
		$user	=	$this->User->find('first', $options);
		$this->set('user', $user);
		if (!$user) {
			throw new NotFoundException(__('Invalid user'));
		}
		
		$options = array('order'=>'RAND()','limit'=>3,'recursive' => -1,'conditions' => array('Property.user_id'=>$id));
		//pr($this->Property->find('all', $options));
		$this->set('agent_properties', $this->Property->find('all', $options));

	}

 	public function edit_agent_profile() {
		//$this->Session->destroy();
		 $this->set('title_for_layout', 'My Profile');
		$id	=	$this->Auth->user('id');

		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}

		if ($this->request->is(array('post', 'put'))) {
			$this->request->data['User']['id']	=	$id;
			if ($this->User->save($this->request->data)) {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$user	=	 $this->User->find('first', $options);
			$this->Session->write('Auth', $user);
				
				
				
				$this->Session->setFlash(__('The user has been saved.'), 'default', array('class' => 'alert alert-success'));
				return $this->redirect(array('action' => 'edit_agent_profile'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error', array('class' => 'alert alert-danger'));
			}
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$user	=	 $this->User->find('first', $options);
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $user	=	 $this->User->find('first', $options);
		}
		$this->set('user',$user);
	}



	public function forgot_password() {
		$this->set('title_for_layout', 'Forgot your password?');
		$this->User->validate = array('email' => array(
							'required' => array(
								'rule' => array('notEmpty'),
								'message' => 'A email is required'
							),
							'email' => array(
								'rule' => array('email'),
								'message' => 'Enter valid mail address'
							)
					));

			if ($this->request->is('post')) {
				$data = $this->request->data;
				$this->User->set($data);
				if ($this->User->validates()) {
					$email	=	$data['User']['email'];
					$data	=	$this->User->findByEmailAndActive($email,1);
					if(!empty($data)){
							$id	=	$data['User']['id'];
							$user['User']['tokken']	=	 Security::generateAuthKey().''.Security::generateAuthKey();
							$user['User']['id']		=	 $id;
							if($this->User->save($user)){
								$data['User']['tokken']	=$user['User']['tokken'];
								 $result	=	array_merge($user, $data);
								 $this->email_forgot_password($result);
								$this->Session->setFlash(__('Tokken has been sent to your Email. Please check your email. and follow instructions'));
								return $this->redirect(array('action'=>'forgot_password'));
							}
					}else
					{
						$this->Session->setFlash(__('Invalid Email, try again'),'error');
						return $this->redirect(array('action'=>'forgot_password'));
					}
				
				} else {
					$errors = $this->User->validationErrors;
				}
				
				}
		}


    private function email_forgot_password($User=array()) {
		if(isset($User) and !empty($User))
		{
			
			$website_name	=	$this->viewVars['websiteSettings']['website_name'];
			$websiteSettings	=	$this->viewVars['websiteSettings'];
			$website_name	=	$websiteSettings['website_name'];
			$noreply_email	=	$websiteSettings['noreply_email'];
			$email = new CakeEmail();
			$email->from(array($noreply_email => $website_name))
			->to($User['User']['email'])
			->subject($website_name.'  Forgot Password')
			->template('email_forgot_password')
			->emailFormat('html')
			->viewVars(array('User' => $User))
			->send();
    		 $this->Session->setFlash(__('Tokken has been sent to your Email. Please check your email. and follow instructions in  <b>'.$User['User']['email'].'</b>'));
			return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
		}
		return true;
	}
    
	
	private function email_registered($User=array()) {
		if(isset($User) and !empty($User))
		{
			
			$website_name	=	$this->viewVars['websiteSettings']['website_name'];
			$websiteSettings	=	$this->viewVars['websiteSettings'];
			$website_name	=	$websiteSettings['website_name'];
			$noreply_email	=	$websiteSettings['noreply_email'];
			$email = new CakeEmail();
			$email->from(array($noreply_email => $website_name))
			->to($User['User']['email'])
			->subject($website_name.' You have registered successfully')
			->template('email_registered')
			->emailFormat('html')
			->viewVars(array('User' => $User))
			->send();
    		 $this->Session->setFlash(__('Authntication email been sent to your Email. Please check your email. and follow instructions in  <b>'.$User['User']['email'].'</b>'));
			return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
		}
		return true;
	}

		public function email_verification($tokken=null) {
		$this->set('title_for_layout', 'Email verification');
			if(isset($tokken) and !empty($tokken) and ctype_alnum($tokken)){
				$User	=	$this->User->findByTokkenAndActive($tokken,1);
				if($User){
						$this->User->id	=	$User['User']['id'];
						$data['User']['tokken']	=	'';
					//	$data['User']['approved']	=	1;
					//	$data['User']['active']	=	1;
						$data['User']['email_verified']	=	1;
								if($this->User->save($data)){
								$this->Session->setFlash(__('Your Email has been verified for <b>'.$User['User']['email'].'</b>. Please you can login to system'));
								 return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
								}
				}
				else
					{
                    return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
					}
			}
			else
			{
                    return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
			}

	}

		public function reset_password($tokken=null) {
		$this->set('title_for_layout', 'Reset Password');
			$this->User->validate = array(
								'password' => array(
									'notEmpty' => array(
										'rule'    => array('minLength', '5'),
										'message' => 'Minimum 5 characters long',
								), 
									'alphaNumeric' => array(
									'rule' => 'alphaNumeric',
									'required' => true,
									'message' => 'Letters and numbers only'
								),
									),
									're_password' => array(
										'notEmpty' => array(
										'rule'    => array('minLength', '5'),
										'message' => 'Minimum 5 characters long',
									),
									'compare'    => array(
										'rule'      => array('validate_passwords'),
										'message' => 'The passwords you entered do not match.',
									)
									));
			
			if(isset($tokken) and !empty($tokken) and ctype_alnum($tokken)){
				$User	=	$this->User->findByTokkenAndActive($tokken,1);
				if($User){
						$this->User->id	=	$User['User']['id'];
						$this->set(compact('User'));
						if ($this->request->is('post')) {
						$data['User']['password'] = $this->request->data['User']['password'];
						$this->request->data['User']['tokken']	=	'';
								if($this->User->save($this->request->data)){
								$this->Session->setFlash(__('Your Password has been reset for <b>'.$User['User']['email'].'</b>.'));
								 return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
								}
						}
				}
				else
					{
                    return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
					}
			}
			else
			{
                    return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
			}

	}


	public function delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			$this->Session->setFlash(__('The user has been deleted.'), 'default', array('class' => 'alert alert-success'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
		}
		return $this->redirect(array('action' => 'index'));
	}

	public function admin_index($user_role	=	'broker_admin') {

		$user_role	=	strtolower(trim($user_role));
		if($user_role=='agent')
		$user_role	=	$user_role;
		else
		$user_role	=	'broker_admin';

		$this->set('title_for_layout', Inflector::humanize(__($user_role)));

		$this->User->recursive = 0;
		$this->paginate = array('order'=>'User.created desc');
		$this->set('users', $this->Paginator->paginate(array('User.user_role'=>array($user_role))));
		$this->set('user_role', $user_role);
	}

	public function admin_view($id = null) {
		$this->set('title_for_layout', 'Detail Agent/Broker');
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
		$this->paginate	=	array('limit'=>1);		
		$this->User->recursive = 0;
		$this->set('users', $this->Paginator->paginate(array('User.broker_id'=>array($id))));

	}

	public function admin_add() {
		$this->set('title_for_layout', 'Add Agent/Broker');
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'), 'default', array('class' => 'alert alert-success'));
				return $this->redirect(array('action' => 'index',$this->request->data['User']['user_role']));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error');
			}

		}

	}
	public function admin_edit($id = null) {
		$this->set('title_for_layout', 'Edit Agent/Broker');
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {

			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$user	=	$this->User->find('first', $options);

			$user_role	=	'';

			if($user['User']['user_role']=='agent')
			$user_role	=	'agent';


			if ($this->User->save($this->request->data)) {
				
				
				$this->Session->setFlash(__('The user has been saved.'), 'default', array('class' => 'alert alert-success'));
			$this->admin_clear_side_cache();
				return $this->redirect(array('action' => 'index',$user_role));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'error', array('class' => 'alert alert-danger'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $user	=	$this->User->find('first', $options);
		}
		$this->set('user',$user);
	}

	public function admin_delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			$this->admin_clear_side_cache();
			$this->Session->setFlash(__('The user has been deleted.'), 'default', array('class' => 'alert alert-success'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'), 'error', array('class' => 'alert alert-danger'));
		}
		return $this->redirect(array('action' => 'index'));
	}


	public function logout() {
		return $this->redirect($this->Auth->logout());
	}

	public function admin_logout() {
		return $this->redirect($this->Auth->logout());
	}

 private function admin_clear_side_cache() {

		//$this->request->onlyAllow('post');

        Cache::clear();
        clearCache();

        $files = array();
       //$files = array_merge($files, glob(CACHE . '')); // remove cached css
        $files = array_merge($files, glob(CACHE . '*')); // remove cached css

//pr($files);
        foreach ($files as $f) {
            if (is_file($f)) {
				
                @unlink($f);
            }
        }

        if(function_exists('apc_clear_cache')):      
        apc_clear_cache();
        apc_clear_cache('user');
        endif;
		 return true;
    }
 public function admin_clear_cache() {

		//$this->request->onlyAllow('post');

        Cache::clear();
        clearCache();

        $files = array();
       //$files = array_merge($files, glob(CACHE . '')); // remove cached css
        $files = array_merge($files, glob(CACHE . '*')); // remove cached css
        $files = array_merge($files, glob(CACHE . 'css' . DS . '*')); // remove cached css
        $files = array_merge($files, glob(CACHE . 'js' . DS . '*'));  // remove cached js           
        $files = array_merge($files, glob(CACHE . 'models' . DS . '*'));  // remove cached models           
        $files = array_merge($files, glob(CACHE . 'persistent' . DS . '*'));  // remove cached persistent           
        $files = array_merge($files, glob(TMP . 'sessions' . DS . '*'));  // remove cached sessions           

//pr($files);
        foreach ($files as $f) {
            if (is_file($f)) {
				
				 // echo $f;
				 // echo '<br/>';
                @unlink($f);
            }
        }

        if(function_exists('apc_clear_cache')):      
        apc_clear_cache();
        apc_clear_cache('user');
        endif;

        $this->set(compact('files'));
        $this->layout = 'ajax';
		 return $this->redirect(array('action' => 'index'));
    }

	public function download() {
		$id	=	$this->Auth->user('id');
		$this->admin_download($id);
		// return $this->redirect(array('action' => 'edit_agent_profile'));
	}
	public function admin_download($id = null) {
			if (!$this->User->exists($id)) {
				throw new NotFoundException(__('Invalid user'));
			}
				$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
				$user	=	$this->User->find('first', $options);
	
		$this->viewClass = 'Media';
		// Render app/webroot/files/example.docx
		$params = array(
			'id'        => $user['User']['documents'],
			'name'      => $user['User']['first_name'].'-'.$user['User']['last_name'].'('.$user['User']['email'].')',
			'download' => 1,
			'path'      => 'files' . DS.'user_doc' . DS
		);
		$this->set($params);
		return true;
	}

}

